<template>
  <!-- 承租商管理-承租商设置（列表） -->
  <div class="mod-seckill-shopAuditing">
    <div class="search-bar">
      <el-form
        @submit.native.prevent
        :inline="true"
        ref="searchForm"
        :model="searchForm"
        size="small"
        :class="
          this.$i18n.t('language') === 'English'
            ? 'en-search-form'
            : 'zh-search-form'
        "
      >
        <div class="input-row setright">
          <el-form-item prop="brandName" :label="$t('brand.brandName') + ':'">
            <el-input
              v-model="searchForm.brandName"
              size="small"
              :placeholder="$t('brand.pleaseEnterBrandName')"
            ></el-input>
          </el-form-item>

          <el-form-item prop="brandName" :label="$t('brand.brandID') + ':'">
            <el-input
              v-model="searchForm.brandCode"
              size="small"
              :placeholder="$t('brand.brandID')"
            ></el-input>
          </el-form-item>


          <!-- <el-form-item prop="brandType" :label="$t('brand.brandType') + ':'">
            <el-select v-model="searchForm.brandType" :placeholder="$t('brand.pleaseEnterbrandType')">
              <el-option :label="$t('brand.selfOperatedBrand')" :value="1"></el-option>
              <el-option :label="$t('brand.chainBrand')" :value="0"></el-option>
            </el-select>
          </el-form-item> -->
          <!--(-1:已删除 0: 停业中 1:营业中 2:平台下线 3:上线待审核 4:开店申请中 5:开店申请待审核)-->
          <el-form-item prop="brandStatusList" :label="$t('brand.brandStatus') + ':'">
            <el-select v-model="searchForm.brandStatusList" :placeholder="$t('brand.pleaseEnterbrandStatus')">
              <el-option :label="$t('shop.inOperation')" :value="1"></el-option>
              <el-option :label="$t('shop.stop')" :value="0"></el-option>
              <!-- <el-option :label="$t('shop.offlineViolation')" :value="2"></el-option>
              <el-option :label="$t('shop.offlinePendingReview')" :value="3"></el-option> -->
            </el-select>
          </el-form-item>

          <el-form-item style="float: right">
            <div class="default-btn primary-btn" @click="searchChange(true)">
              {{ $t("product.search") }}
            </div>
            <div class="default-btn" @click="resetSearchForm('searchForm')">
              {{ $t("product.reset") }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <!-- <div
          v-if="isAuth('brand:brandAuditing:add')"
          class="default-btn primary-btn"
          @click="insertShop()"
        >
          {{ $t("crud.addTitle") }}
        </div>
        <div
          v-if="isAuth('brand:brandAuditing:export')"
          class="default-btn primary-btn"
          @click="exportShop()"
        >
          {{ $t("formData.export") }}
        </div> -->
      </div>
      <div class="table-con audit-shop-table">
        <div v-if="dataList.length === 0" class="empty-text">
          {{ $t("user.noData") }}
        </div>
        <el-table
          :key="tabValue"
          ref="auditShop"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
          <el-table-column
            align="center"
            prop="index"
            :label="$t('formData.serialNumber')"
            width="60"
            type="index"
          />
          <el-table-column
            align="center"
            prop="brandName"
            :label="$t('brand.brandName')"
          >
            <template slot-scope="scope">
              <div class="table-cell-con">
                <span class="table-cell-text">{{ scope.row.brandName }}</span>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column
            align="center"
            prop="brandType"
            :label="$t('brand.brandType')"
            width="auto">
            <template slot-scope="scope"> -->
          <!-- 承租商类型(0:连锁承租商 1:自营承租商) -->
          <!-- <span class="tag-text">{{[$t('brand.chainBrand'),$t('brand.selfOperatedBrand')][scope.row.brandType]}}</span>
            </template>
          </el-table-column> -->
          <el-table-column
            align="center"
            prop="brandCode"
            :label="$t('brand.brandID')"
          >
          </el-table-column>
          <!-- <el-table-column
            align="center"
            prop="brandLogo"
            :label="$t('brand.brandLogo')"
            width="160"
          >
            <template slot-scope="scope">
              <img
                :src="getImgSrc(scope.row.brandLogo)"
                style="width: 60px; height: 60px"
                @error="handlePicError"
              />
            </template>
          </el-table-column> -->
          <!-- <el-table-column
            align="center"
            prop="intro"
            :label="$t('brand.brandProfile')"
            width="280">
            <template slot-scope="scope">
              <span v-if="scope.row.intro" class="table-cell-text">{{ scope.row.intro }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="createTime"
            :label="$t('brand.applicationTime')"
            min-width="100">
          </el-table-column> -->
          <el-table-column
            align="center"
            prop="brandStatus"
            :label="$t('brand.brandStatus')"
          >
            <template slot-scope="scope">
              <!-- 承租商状态(-1:已删除 0: 停业中 1:营业中 2:平台下线 3:平台下线待审核 4:开店申请中 5:开店申请待审核) -->
              <span v-if="scope.row.brandStatus === -1" class="tag-text">{{
                $t("shop.deleted")
              }}</span>
              <span v-else-if="scope.row.brandStatus === 0" class="tag-text">{{
                $t("shop.stop")
              }}</span>
              <span v-else-if="scope.row.brandStatus === 1" class="tag-text">{{
                $t("shop.inOperation")
              }}</span>
              <span v-else-if="scope.row.brandStatus === 2" class="tag-text">{{
                $t("shop.offlineViolation")
              }}</span>
              <span
                v-else-if="
                  scope.row.brandStatus === 3 || scope.row.brandStatus === 5
                "
                class="tag-text"
                >{{ $t("shop.offlinePendingReview") }}</span
              >
              <span v-else-if="scope.row.brandStatus === 4" class="tag-text">{{
                $t("distributionMsg.applying")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            fixed="right"
            :label="$t('publics.operating')"
          >
            <template slot-scope="scope">
              <div class="">
                <!-- 详情 -->
                <!-- <div
                  v-if="isAuth('brand:brandAuditing:detail')"
                  class="default-btn text-btn"
                  @click="auditHandle(scope.row.brandId, 0)"
                >
                  {{ $t("brand.details") }}
                </div> -->
                <!-- 编辑 -->
                <!-- <div
                  v-if="isAuth('brand:brandAuditing:edit')"
                  class="default-btn text-btn"
                  @click="auditHandle(scope.row.brandId, 1)"
                >
                  {{ $t("coupon.edit") }}
                </div> -->
                <!-- 下线承租商 -->
                <!-- <div
                  class="default-btn text-btn"
                  v-if="
                    scope.row.brandStatus <= 1 &&
                    isAuth('brand:brandAuditing:offline')
                  "
                  @click="offlineHandle(scope.row)"
                >
                  {{ $t("brand.offlineBrand") }}
                </div> -->
                <!-- 下线管理 -->
                <!-- <div
                  class="default-btn text-btn"
                  v-if="
                    scope.row.brandStatus > 1 &&
                    isAuth('brand:brandAuditing:offline')
                  "
                  @click="shopAuditHandle(scope.row.brandId)"
                >
                  {{
                    scope.row.brandStatus === 2
                      ? $t("distributionProdLog.offlineManagement")
                      : $t("product.pendingReview")
                  }}
                </div> -->
                <!-- 账号管理 -->
                <div
                  class="default-btn text-btn"
                  v-if="isAuth('brand:brandAuditing:accountManagement')"
                  @click="shopAccountHandle(scope.row.brandId)"
                >
                  {{ $t("shop.accountManagement") }}
                </div>
              </div>
            </template>
          </el-table-column>

          <div slot="empty">&nbsp;</div>
        </el-table>
      </div>
      <el-pagination
        v-if="dataList.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
    </div>
    <!-- 下架管理 -->
    <offline-manage
      v-if="offlineDialogVisible"
      ref="offlineData"
      @refreshDataList="refreshChange"
    />
    <!-- 账号管理 -->
    <ShopAccount
      v-if="shopAccountVisible"
      ref="shopAccount"
      @refreshDataList="refreshChange"
    ></ShopAccount>
    <!-- 导出承租商 -->
    <el-dialog
      :title="$t('shopProcess.exportBrand')"
      :visible.sync="exportShopVisible"
    >
      <el-radio v-model="exportRadio" label="1">{{
        $t("shopProcess.exportSearchBrand")
      }}</el-radio>
      <el-radio v-model="exportRadio" label="2">{{
        $t("shopProcess.exportSelectBrand")
      }}</el-radio>
      <span slot="footer" class="dialog-footer">
        <div class="default-btn" @click="exportShopVisible = false">
          {{ $t("coupon.cancel") }}
        </div>
        <div
          class="default-btn primary-btn"
          type="primary"
          @click="confirmExport"
        >
          {{ $t("coupon.confirm") }}
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import offlineManage from "./brand-offline-manage";
import ShopAccount from "./brand-account.vue";
export default {
  data() {
    return {
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      theData: null, // 保存上次点击查询的请求条件
      theParams: null, // 保存上次点击查询的请求条件
      dataList: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      searchForm: {
        brandName: undefined,
        intro: undefined,
        type: undefined,
        merchantMobile: undefined,
      }, // 搜索
      dateRange: [],
      dataListSelections: [],
      dataListLoading: false,
      shopAuditVisible: false,
      shopAccountVisible: false,
      exportShopVisible: false,
      exportRadio: "1",
      isSubmit: false,
      shopStatusShow: [
        "",
        this.$i18n.t("shop.inOperation"),
        this.$i18n.t("shop.offlineViolation"),
      ],

      offlineDialogVisible: false,
    };
  },
  props: {
    tabValue: {
      type: String,
      default: "",
    },
  },
  components: {
    // ShopAudit,
    offlineManage,
    ShopAccount,
  },
  created() {
    this.getDataList();
  },
  mounted() {},
  methods: {
    getDataList(page, newData = false) {
      page = page || this.page;
      if (newData || !this.theData) {
        this.theData = {
          current: page.currentPage,
          size: page.pageSize,
        };
        this.theParams = JSON.parse(JSON.stringify(this.searchForm));
        this.theParams.brandStatusList =
          this.theParams.brandStatusList !== null &&
          this.theParams.brandStatusList !== undefined
            ? this.theParams.brandStatusList
            : [0, 1, 2, 3];
      } else {
        this.theData.current = page.currentPage;
        this.theData.size = page.pageSize;
      }

      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/platform/brand/page"),
        method: "get",
        params: this.$http.adornParams(
          Object.assign(this.theData, this.theParams)
        ),
      }).then(({ data }) => {
        this.dataList = data.records;
        this.page.total = data.total;
        this.page.currentPage = data.current;
        this.dataListLoading = false;
      });
    },
    /**
     * 查看 / 审核
     * @param id 店铺id
     * @param type 0查看 1编辑
     */
    auditHandle(id, type) {
      if (type === 1) {
        this.$router.push({
          path: "/platform-brand/auditBrand-edit",
          query: { brandId: id },
        });
      } else {
        this.$router.push({
          path: "/platform-brand/auditBrand-detail",
          query: { brandId: id },
        });
      }
    },
    // 账号管理
    shopAccountHandle(id) {
      this.shopAccountVisible = true;
      this.$nextTick(() => {
        this.$refs.shopAccount.init(id);
      });
    },

    /**
     * 新增店铺
     */
    insertShop() {
      this.$router.push({ path: "/platform-shopProcess/shopProcess" });
    },
    /**
     * 导出店铺
     */
    exportShop() {
      this.exportShopVisible = true;
    },
    // 多选变化
    handleSelectionChange(val) {
      this.dataListSelections = val;
      this.selectAll = val.length === this.dataList.length;
    },
    /**
     * 确定导出
     */
    confirmExport() {
      if (this.exportRadio !== "1" && this.exportRadio !== "2") {
        this.$message({
          message: this.$i18n.t("shop.exportRadioEmptyTips"),
          type: "error",
          duration: 1500,
          onClose: () => {
            this.isSubmit = false;
          },
        });
        return;
      }
      if (this.isSubmit) {
        return;
      }
      this.isSubmit = true;
      // 准备参数
      let params = {};
      if (this.exportRadio === "1") {
        // 导出模式为按搜索条件导出
        if (this.page.total === 0) {
          this.$message({
            message: this.$i18n.t("shop.exportShopSearchEmptyTips"),
            type: "error",
            duration: 1500,
            onClose: () => {
              this.isSubmit = false;
            },
          });
          return;
        }
        // 赋值搜索参数
        params = JSON.parse(JSON.stringify(this.searchForm));
        params.shopStatusList =
          params.brandStatusList !== null &&
          params.brandStatusList !== undefined
            ? params.brandStatusList
            : [0, 1, 2, 3];
        params.shopName = params.brandName;
        params.shopIds = undefined;
        params.brandStatusList = undefined;
        params.brandName = undefined;
      } else {
        // 导出模式为按选中的店铺导出
        if (this.dataListSelections.length === 0) {
          this.$message({
            message: this.$i18n.t("shop.exportShopSelectEmptyTips"),
            type: "error",
            duration: 1500,
            onClose: () => {
              this.isSubmit = false;
            },
          });
          return;
        }
        // 赋值选中的店铺id
        params.shopIds = this.dataListSelections.map((item) => {
          return item.brandId;
        });
      }
      const loading = this.$loading({
        lock: true,
        target: ".mod-seckill-shopAuditing",
        customClass: "export-load",
        background: "transparent",
        text: this.$i18n.t("shop.exportIng"),
      });
      this.$http({
        url: this.$http.adornUrl("/platform/brand/exportBrand"),
        method: "get",
        params: this.$http.adornParams(params),
        responseType: "blob",
      })
        .then(({ data }) => {
          loading.close();
          let blob = new Blob([data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
          });
          const fileName = this.$i18n.t("brand.comInfoSorXls");
          const elink = document.createElement("a");
          if ("download" in elink) {
            elink.download = fileName;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
          } else {
            navigator.msSaveBlob(blob, fileName);
          }
          this.$message({
            message: this.$i18n.t("shop.exportSuccess"),
            type: "success",
            duration: 1500,
            onClose: () => {
              this.isSubmit = false;
              this.exportShopVisible = false;
            },
          });
        })
        .catch((e) => {
          loading.close();
          this.isSubmit = false;
        });
    },
    // 下架店铺
    offlineHandle(row) {
      // 确定对承租商[' + row.shopName + ']进行下线操作？如是，请填写下线理由
      var tips = this.$i18n.t("brand.brandTip1");
      tips = tips.replace("SHOPNAME", row.brandName);
      this.$prompt(tips, this.$i18n.t("text.tips"), {
        confirmButtonText: this.$i18n.t("coupon.confirm"),
        cancelButtonText: this.$i18n.t("coupon.cancel"),
        inputPattern: /\s\S+|S+\s|\S/, // 不能全为空格 空字符串
        inputErrorMessage: this.$i18n.t("seckill.offlineReasonTip"),
        inputValidator: (value) => {
          if (value.length > 100) {
            return this.$i18n.t("seckill.offlineReasonTip1");
          }
        },
      }).then((obj) => {
        this.$http({
          url: this.$http.adornUrl(`/platform/brand/offline`),
          method: "post",
          data: this.$http.adornData({
            handleId: row.brandId,
            handleType: 3,
            offlineReason: obj.value || null,
          }),
        }).then(({ data }) => {
          this.$message({
            message: this.$i18n.t("publics.operation"),
            type: "success",
            duration: 1500,
            onClose: () => {
              this.getDataList(this.page);
            },
          });
        });
      });
    },
    /**
     * 刷新回调
     */
    refreshChange() {
      this.getDataList(this.page);
    },
    // 清空自定义数据
    searchReset() {
      this.searchForm = {}
      this.dateRange = [];
    },
    searchChange(newData = false) {
      this.page.currentPage = 1;
      this.getDataList(this.page, newData);
    },
    // 弹窗处理
    shopAuditHandle(id) {
      // this.shopAuditVisible = true
      // this.$nextTick(() => {
      //   this.$refs.shopAudit.init(id)
      // })
      this.getOfflineDetailByShopId(id);
    },

    /**
     * 获取最新店铺下线事件
     */
    getOfflineDetailByShopId(shopId) {
      this.offlineDialogVisible = true;
      this.$http({
        url: this.$http.adornUrl(
          `/platform/brand/getOfflineHandleEventByBrandId/${shopId}`
        ),
        method: "GET",
      }).then(({ data }) => {
        this.offlineDetail = data;
        this.$nextTick(() => {
          this.$refs.offlineData.init(data, shopId);
        });
      });
    },

    getImgSrc(img) {
      if (!img) {
        return "";
      }
      if (img.indexOf("http://") === 0 || img.indexOf("https://") === 0) {
        return img;
      }
      return this.resourcesUrl + img;
    },
    /**
     * 当图片加载失败时，切换至默认图
     */
    handlePicError(event) {
      event.target.src = require("@/assets/img/shop-logo-def.png");
    },

    /**
     * 重置表单
     * @param {String} formName 表单名称
     */
    resetSearchForm(formName) {
      this.$refs[formName].resetFields();
      this.searchReset();
    },

    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getDataList();
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.getDataList();
    },
  },
};
</script>
<style lang="scss" scoped>
.mod-seckill-shopAuditing {
  .search-bar {
    // .en-search-form {
    //   & ::v-deep .el-form-item__label {
    //     width: 120px;
    //   }
    // }
    // .zh-search-form {
    //   & ::v-deep .el-form-item__label {
    //     width: 90px;
    //   }
    // }
  }
}

.table-con {
  position: relative;
}

.empty-text {
  position: absolute;
  z-index: 4;
  top: 50%;
  left: 50%;
  color: #909399;
}
::v-deep .export-load {
  top: -50% !important;
}
</style>

<style scoped>
>>> .el-table__fixed-right::before {
  z-index: 0;
}
</style>
